import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import './Captcha.css';

const Captcha = ({ onValidate, error }) => {
  const { t } = useTranslation();
  const [captchaCode, setCaptchaCode] = useState('');
  const [userInput, setUserInput] = useState('');
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Generate a random captcha code
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    let code = '';
    for (let i = 0; i < 6; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
  };

  // Refresh captcha
  const refreshCaptcha = () => {
    setIsRefreshing(true);
    setTimeout(() => {
      setCaptchaCode(generateCaptcha());
      setUserInput('');
      setIsRefreshing(false);
    }, 300);
  };

  // Initialize captcha on mount
  useEffect(() => {
    setCaptchaCode(generateCaptcha());
  }, []);

  // Validate captcha when user input changes
  useEffect(() => {
    if (onValidate) {
      onValidate(userInput === captchaCode);
    }
  }, [userInput, captchaCode, onValidate]);

  const handleInputChange = (e) => {
    setUserInput(e.target.value);
  };

  return (
    <div className="captcha-container">
      <div 
        className={`captcha-image ${isRefreshing ? 'refreshing' : ''}`}
        onClick={refreshCaptcha}
        title={t('captcha.refresh')}
      >
        {captchaCode.split('').map((char, index) => (
          <span 
            key={index} 
            style={{
              display: 'inline-block',
              transform: `rotate(${Math.random() * 20 - 10}deg)`,
              color: `hsl(${Math.random() * 60 + 200}, 70%, 50%)`,
              fontSize: `${Math.random() * 4 + 16}px`,
              marginLeft: index > 0 ? '2px' : '0'
            }}
          >
            {char}
          </span>
        ))}
      </div>
      
      <button 
        type="button" 
        className="captcha-refresh"
        onClick={refreshCaptcha}
        title={t('captcha.refresh')}
      >
        🔄
      </button>
      
      <input
        type="text"
        className="form-input captcha-input"
        placeholder={t('captcha.placeholder')}
        value={userInput}
        onChange={handleInputChange}
        maxLength={6}
      />
      
      {error && (
        <span className="error-message">{error}</span>
      )}
    </div>
  );
};

export default Captcha;